package com.xw.base.config;


import com.xw.base.client.RedisClient;
import com.xw.base.entity.exception.BoException;
import com.xw.base.entity.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisClient redisClient;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        String jsessionid = httpServletRequest.getHeader("JSESSIONID1");

        if (StringUtils.isEmpty(jsessionid)) {
//            throw new BoException(new CustomException("403", "token错误"));
            // 暂时先不使用权限
            return true;
        }

        long expire = redisClient.getExpire(jsessionid);

        // 操作过程中，自动延长过期时间
        if (expire < 3600) {

            int index = jsessionid.indexOf("-");
            String userId = jsessionid.substring(0,index);

            redisClient.expire(jsessionid, 7200);
            redisClient.expire(userId,7200);
        }

        Object o = redisClient.get(jsessionid);
        if (null == o) {
            throw new BoException(new CustomException(403, "未登陆"));
        }

        return true;
    }

}
